package com.smm.web.vmc.tool;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;


/**
 * 远程下载图片
 */
public class GetImage {

    public static void writeImageToDisk(byte[] img, String fileName, String savePath) {
        try {
            File file = new File(savePath + fileName);
            FileOutputStream fops = new FileOutputStream(file);
            fops.write(img);
            fops.flush();
            fops.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static byte[] getImageFromNetByUrl(String strUrl) {
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5000);
            InputStream inStream = conn.getInputStream();
            return readInputStream(inStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] readInputStream(InputStream inStream)
            throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    public static void main(String[] args) {
        String url = "http://www.baidu.com/img/baidu_sylogo1.gif";

        url = "http://img.ys7.com/group4/M00/2D/A8/CmFnglqp8aeAEWrBAAB5EA7Ojmo416.jpg";
        byte[] btImg = getImageFromNetByUrl(url);
        if ((null != btImg) && (btImg.length > 0)) {
            System.out.println("读取到：" + btImg.length + " 字节");
            String fileName = "test.jpg";
            writeImageToDisk(btImg, fileName, "d:\\");
            System.out.println("图片保存成功");
        } else {
            System.out.println("没有从该连接获得内容");
        }
    }
}